/*
 * @Author: czy
 * @Date: 2021-04-29 16:32:34
 * @LastEditTime: 2021-05-04 15:50:39
 */
#include "mystdio.h"
#include "exception.h"

void test_throw_exception(int num)
{
    if (num == 0)
    {
        throw;
    }
    else
    {
        myPutchar('*');
        test_throw_exception(num - 1);
    }
}

/**
 * @description: Test the exception handler.
 * There are four situations:
 * 1. Create an exception `Divide By Zero` and throw it in the interrupt handler; 
 * 2. Apply two layers of `try`... `catch` block;
 * 3. Throw an exception in a function that iterates several times;
 * 4. do not throw an exception in try block.
 */
void test_exception(void)
{
    try
    {
        myprintf("Try to divide zero: ");
        int i = 1, j = 0, k;
        k = i / j;
        myprintf("success\n");
    }
    catch
    {
        myprintf("fail\n");
    }

    try
    {
        myprintf("Throw and catch an exception: ");
        try
        {
            myprintf("[throw:");
            throw;
        }
        catch
        {
            myprintf("catch]");
        }
        myprintf("success\n");
    }
    catch
    {
        myprintf("fail\n");
    }

    try
    {
        myprintf("Throw an exception in function: ");
        test_throw_exception(5);
        myprintf("success\n");
    }
    catch
    {
        myprintf("fail\n");
    }

    try
    {
        myprintf("Do not throw an exception: ");
        myprintf("success\n");
    }
    catch
    {
        myprintf("fail\n");
    }

    // Unhandle error
    // int k = 0;
    // k = 1 / k;
}